<?php

function reset_all_cont()
{
    global $dbh;
    global $user;

    $sth = $dbh->prepare('insert into cmd_queue (uid, c_id, cmd, param, user) values (UUID(),:cid,:cmd, :param, :user)');

    $res = $dbh->query('select c_id, job_mode from network_map where online=1');

    $rec = $res->fetchAll(PDO::FETCH_ASSOC);

    $setprog = 18;
    $setphase = 23;
    $param = 0;
    
    foreach($rec as $key => $value)
    {
        switch ($value['job_mode'])
        {
            case 1:
            case 2:

                $sth->bindParam(':cid', $value['c_id'], PDO::PARAM_INT);
                $sth->bindParam(':cmd', $setphase, PDO::PARAM_INT);
                $sth->bindParam(':param', $param, PDO::PARAM_INT);
                $sth->bindParam(':user', $user['login']);

                $sth->execute();

            case 6:

                $sth->bindParam(':cid', $value['c_id'], PDO::PARAM_INT);
                $sth->bindParam(':cmd', $setprog, PDO::PARAM_INT);
                $sth->bindParam(':param', $param, PDO::PARAM_INT);
                $sth->bindParam(':user', $user['login']);

                $sth->execute();
        }
    }
}

$oper = $_GET['oper'];

if (!isset($oper))
{
    die("Unknown command");
}

$admin = false;
require_once('auth_req.inc.php');



switch ($oper) 
{
    case 'lock':

        try
        {

            $dbh->exec('lock tables disp write');

            $log_msg = "Оператор взял управление";

            if (isset($_GET['force']) && intval($_GET['force']) == 1)
            {
                $dbh->exec('delete from disp');

                $log_msg = "Оператор [принудительно] взял управление";
            }
            else
            {
                $rs = $dbh->query('select login, DATE_FORMAT(date,"%d.%m.%Y %H:%i") as date from disp limit 1');
                                                       
                if ($rec = $rs->fetchAll())
                {
                    $responce->force = true;
                    throw new Exception('Диспетчерское управление у пользователя: '.$rec[0]['login'].' оно взято : '.$rec[0]['date']);
                }
            }

            $sth = $dbh->prepare('insert into disp (idsession, login, date) values (:idsession, :login, NOW())');

            $sth->bindParam(':login',$user['login']);

            $sth->bindParam(':idsession',$auth->getSessId());

            $sth->execute();

            $dbh->exec('unlock tables');

            $sth = $dbh->prepare('insert into log (log_date,log_type, imp, user,log_msg) values (NOW(),0,0,:user,"'.$log_msg.'")');

            $sth->execute(array('user'=> $user['login']));

            $responce->status = 'Выполнена команда перехода в режим ДУ !';
        }
        catch (Exception $e)
        {
            $dbh->exec('unlock tables');
            $responce->error = $e->getMessage();
        }

        break;

    case 'free':

        try
        {

            $dbh->exec('lock tables disp write, events write');

            $sth = $dbh->prepare('select count(*) from disp where idsession= :idsession limit 1');

            $cook = $auth->getCookie();

            $sth->bindParam(':idsession',$cook['value']);

            $sth->execute();

            if ($sth->fetchColumn() > 0)
            {
                $dbh->exec('delete from disp'); // cleanup
            }

            $dbh->exec('update events set act=0');

            $dbh->exec('unlock tables');

            $sth = $dbh->prepare('insert into log (log_date,log_type, imp, user,log_msg) values (NOW(),0,0,:user,"Оператор отдал управление")');

            $sth->execute(array('user'=> $user['login']));

            reset_all_cont();

            $responce->status = 'Выполнена команда выхода из режима ДУ !';
        }
        catch (Exception $e)
        {
            $dbh->exec('unlock tables');
            $responce->error = $e->getMessage();
        }

        break;

    case 'check':

        try
        {
            $sth = $dbh->prepare('select count(*) from disp where idsession= :idsession limit 1');

            $sth->bindParam(':idsession',$auth->getSessId());

            $sth->execute();

            if ($sth->fetchColumn() > 0)
            {
                $responce->disp = true;

            }
            else
            {
                $responce->disp = false;
            }
        }
        catch (Exception $e)
        {
            $responce->disp = false;
        }

        break;
}

echo json_encode($responce);

?>